package cao.oschina.bean;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

/**
 * 登录结果
 * <p/>
 * Created by Haidy on 15/4/6.
 */
public class Result {

    public String errorCode;
    public String errorMessage;

    /**
     * 解析登录结果并返回
     *
     * @param xml xml
     * @return 登录结果
     */
    public static Result parser(String xml) {
        Result result = new Result();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new ByteArrayInputStream(xml.getBytes()));
            Element root = document.getDocumentElement();
            Node noticeNode = root.getElementsByTagName("result").item(0);
            NodeList list = noticeNode.getChildNodes();
            for (int i = 0; i < list.getLength(); i++) {
                if (list.item(i).getNodeType() == Node.ELEMENT_NODE) {
                    Node node = list.item(i);
                    switch (node.getNodeName()) {
                        case "errorCode":
                            result.errorCode = node.getFirstChild().getNodeValue();
                            break;
                        case "errorMessage":
                            result.errorMessage = node.getFirstChild().getNodeValue();
                            break;
                        default:
                            break;
                    }
                }
            }
        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        return result;
    }
}
